package teaching.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import teaching.exception.NotAllowException;
import teaching.mapper.UserMapper;
import teaching.pojo.Student;
import teaching.pojo.User;
import teaching.util.JwtUtil;
import teaching.util.ThreadLocalUtil;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:20201002983_郑雨蓓
 * Date: 2024/3/2
 * Description:用户登录注册啦
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
    @Resource
    UserMapper userMapper;

    public List<User> findUsers() {
        return userMapper.listAllUsers();
    }

    public String login(User user) {
        User dbuser = userMapper.findByUserName(user.getUsername());
        if (dbuser == null) {
            throw new NotAllowException("用户名或密码错误");//自定义异常信息
        }
        if (!user.getPassword().equals(dbuser.getPassword())) {
            throw new NotAllowException("用户名或密码错误");//自定义异常信息
        }
        //登录成功
        // 给令牌权限以后让管理员分配才行
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", user.getUsername());
        String token = JwtUtil.getToken(claims);
        System.out.println("jwt token令牌: " + token);
        return token;
    }

    public User getUserInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User dbuser = userMapper.findByUserName(username);
        if (dbuser == null) {
            throw new NotAllowException("用户信息存在错误");//自定义异常信息
        }
        return dbuser;
    }

    public String getUserName(long userId) {
        return userMapper.findUserName(userId);
    }
}
